URL = "http://downloads.sourceforge.net/project/collada-dom/Collada%%20DOM/Collada%%20DOM%%20%(VERSION)s/Collada%%20DOM%%20%(VERSION)s.zip"
#http://downloads.sourceforge.net/project/collada-dom/Collada%20DOM/Collada%20DOM%202.2/Collada%20DOM%202.2.zip
DEFAULT_VERSION = "2.2"
VERSIONS = ["2.2"]
DEPENDS = ["boost", "zlib", "minizip", "libxml2", "pcre"]


import os, shutil
from source.builders import GenericBuilder, VisualStudioBuilder

class ColladaDomCustomBuilder( GenericBuilder ):
  """ subclass of ConfigureMakeBuilder with custom configure step """

  def targetpath(self):
    return self.directories.enviro + os.sep + "Collada-DOM-%(VERSION)s" % {"VERSION" : self.version}

  def make(self ):
    os.chdir( self.extractedpath )
    print "making collada-dom: ", self.extractedpath

    #note: domasset.h should be domAsset.h    
    if os.path.exists(self.extractedpath+"/dom/include/1.4/dom/domasset.h"):
      shutil.move(self.extractedpath+"/dom/include/1.4/dom/domasset.h", self.extractedpath+"/dom/include/1.4/dom/domAsset.h")

    boost_include = self.dependencies["boost"].getincludedir()
    libxml2_include = self.dependencies["libxml2"].getincludedir()+os.sep+"libxml2"
    pcre_include = self.dependencies["pcre"].getincludedir()
    os.environ["CPLUS_INCLUDE_PATH"] = os.pathsep.join([boost_include, libxml2_include, pcre_include])

    boost_lib = self.dependencies["boost"].getlibdir()
    libxml2_lib = self.dependencies["libxml2"].getlibdir()
    pcre_lib = self.dependencies["pcre"].getlibdir()
    minizip_lib = self.dependencies["minizip"].getlibdir()
    os.environ["LIBRARY_PATH"] = os.pathsep.join([boost_lib, libxml2_lib, pcre_lib, minizip_lib])
    
    self.execute( "cp Makefile.linux Makefile")
    #self.execute( "make prefix="+self.targetpath+" os=linux project=minizip")
    self.execute( "make prefix="+self.targetpath()+" os=linux project=dom -C dom/ " )
    if not os.path.exists(self.targetpath()+os.sep+"include"):
      os.makedirs( self.targetpath()+os.sep+"include" )
      os.makedirs( self.targetpath()+os.sep+"lib" )
    self.execute( "make install prefix="+self.targetpath()+" -C dom/")
    #todo use our own external libs (like with the windows version)

class ColladaDomWinCustomBuilder( VisualStudioBuilder ):
  """ subclass of ConfigureMakeBuilder with custom configure step """

  def __init__(self, runtime):
    super(ColladaDomWinCustomBuilder, self).__init__(runtime)
    if self.machine.isVS2008():
      self.version, self.vcversion = "vc9-1.4", "vc9"
    else:
      self.version, self.vcversion = "vc8-1.4", "vc9"

  def targetpath(self):
    return self.directories.enviro + os.sep + "Collada-DOM-%(VERSION)s" % {"VERSION" : self.version}

  def hasdebug(self):
    return False
    
  def convertProjTo64(self, vcproj):
    if self.machine.bits == 64:
      #collada-dom project is organized differently then most, replace this
      #line before the other replacements (we might want to switch to an xml parser)
      self.replaceInFile( vcproj, [ ("|Win32", "|x64") ] )
      self.replaceInFile( vcproj, [ ("\"Win32\"", "\"x64\"") ] )
      self.replaceInFile( vcproj, [ ("BasicRuntimeChecks=\"3\"", "BasicRuntimeChecks=\"3\" TargetEnvironment=\"3\"") ] )
      self.replaceInFile( vcproj, [ ("TargetMachine=\"1\"", "TargetMachine=\"17\"") ] )

  def create3rdParty( self ):
    os.chdir(self.extractedpath+"\\dom")

    self.boost_version_short = '_'.join(self.dependencies["boost"].version.split('_')[0:2])
    
    #get the directories of the 3rd party libs from the other modules
    #import build_minizip, build_pcre, build_libxml2, build_zlib, build_boost
    #minizip_dir = build_minizip.getminizipdir(self.machine, self.directories)
    #pcre_dir = build_pcre.getpcredir(self.machine, self.directories)
    #libxml2_dir = build_libxml2.getlibxml2dir(self.machine, self.directories)
    #zlib_dir = build_zlib.getzlibdir(self.machine, self.directories)
    #boost_dir = build_boost.getboostdir(self.machine, self.directories) #iconv_dir = build_iconv.geticonvdir(self.machine, self.directories) #no iconv support currently
    
    #print( minizip_dir )
    #print( pcre_dir )
    #print( libxml2_dir )
    #print( zlib_dir )
    #print( boost_dir )
    #print( iconv_dir ) #no iconv support currently
    
    extdir = self.extractedpath+"\\dom\\external-libs"
    if os.path.exists(extdir+"_created"):
      print "Removing previously created: ", extdir+"_created"
      shutil.rmtree(extdir+"_created")

    if os.path.exists(extdir+"_bak"):
      shutil.rmtree( extdir, ignore_errors=True )
      shutil.move( extdir+"_bak", extdir )
            
    try:
        shutil.move( "external-libs", "external-libs_bak" )
                
        os.mkdir( extdir )
        
        #minizip
        shutil.copytree( self.dependencies["minizip"].targetpath(), extdir+"\\minizip" )
        shutil.move( extdir+"\\minizip\\lib", extdir+"\\minizip\\win32\\lib" )
        
        #libxml2
        shutil.copytree( self.dependencies["libxml2"].targetpath(), extdir+"\\libxml2" )
        shutil.move( extdir+"\\libxml2\\lib", extdir+"\\libxml2\\win32\\lib" )
                
        #zlib headers in libxml2
        zlib_dir = self.dependencies["zlib"].targetpath()
        shutil.copy2( zlib_dir+"\\include\\zlib.h", extdir+"\\libxml2\\include" )
        shutil.copy2( zlib_dir+"\\include\\zconf.h", extdir+"\\libxml2\\include" )
        shutil.copy2( zlib_dir+"\\lib\\zlib.lib", extdir+"\\libxml2\\win32\\lib" )
        #shutil.copy2( iconv_dir+"\\lib\\iconv.lib", extdir+"\\libxml2\\win32\\lib" ) #no iconv support currently
        
        #pcre (todo we might want vs8 support)
        shutil.copytree( self.dependencies["pcre"].targetpath(), extdir+"\\pcre" )
        shutil.move( extdir+"\\pcre\\lib", extdir+"\\pcre\\vc9" )
        shutil.move( extdir+"\\pcre\\vc9", extdir+"\\pcre\\lib\\vc9" )
        shutil.move( extdir+"\\pcre\\lib\\vc9\\pcred.lib", extdir+"\\pcre\\lib\\vc9\\pcre-d.lib" )
        shutil.move( extdir+"\\pcre\\lib\\vc9\\pcrecppd.lib", extdir+"\\pcre\\lib\\vc9\\pcrecpp-d.lib" )
        for file in os.listdir( extdir+"\\pcre\\include" ):
          shutil.copy2( extdir+"\\pcre\\include\\" + file, extdir+"\\pcre"  )
        
        #even though we link to the (dynamic) boost with the full name in the enviro folder we copy the files
        #and change the names. This will make the osg find modules work.
        
        boosttargetdir = extdir+"\\boost"+"\\lib\\"+self.vcversion
        os.makedirs(boosttargetdir)
        
        vcversion = {0 : "vc80", 1 : "vc90"}[self.machine.isVS2008()]

        boost_dir = self.dependencies["boost"].targetpath()
        shutil.copy( boost_dir+"\\lib\\boost_filesystem-"+vcversion+"-mt-"+self.boost_version_short+".lib" , boosttargetdir+"\\libboost_filesystem.lib" )
        shutil.copy( boost_dir+"\\lib\\boost_filesystem-"+vcversion+"-mt-gd-"+self.boost_version_short+".lib" , boosttargetdir+"\\libboost_filesystem-d.lib" )
        shutil.copy( boost_dir+"\\lib\\boost_system-"+vcversion+"-mt-"+self.boost_version_short+".lib" , boosttargetdir+"\\libboost_system.lib" )
        shutil.copy( boost_dir+"\\lib\\boost_system-"+vcversion+"-mt-gd-"+self.boost_version_short+".lib" , boosttargetdir+"\\libboost_system-d.lib" )

    except Exception as inst:
        print("Error: "+str(inst))
        exit()
    #finally:    
        #to revert changes (handy during development)
        #shutil.move( "external-libs", "external-libs_created" )
        #shutil.move( "external-libs_bak", "external-libs" )

    try:        
        os.chdir(self.extractedpath)       
        
        #for boost we change the project file to use our (dynamic) version
        replacement1 = [( "..\\..\\external-libs\\boost\\lib\\vc9", boost_dir+"\\lib" ),
        ("libboost_filesystem-d.lib", "boost_filesystem-vc90-mt-gd-"+self.boost_version_short+".lib"),
        ("libboost_system-d.lib", "boost_system-vc90-mt-gd-"+self.boost_version_short+".lib")]        
        replacement2 = [( "..\\..\\external-libs\\boost", boost_dir+"\\include\\boost-"+self.boost_version_short), #TODO shortversion +self.dependencies["boost"].shortversion ),
        ("libboost_filesystem.lib", "boost_filesystem-vc90-mt-"+self.boost_version_short+".lib"),
        ("libboost_system.lib", "boost_system-vc90-mt-"+self.boost_version_short+".lib"),
        #("zlib.lib", "zlib.lib iconv.lib") #no iconv support currently
        ("minizip.lib", "minizip.lib miniunz.lib"), #miniunz.lib was missing
        ("BOOST_ALL_NO_LIB", "BOOST_ALL_DYN_LINK") ]
        
        #always start with the previous orig (move this idea into the builders.py code
        for proj in self.projects:
          if os.path.exists(proj+".orig"):
            os.remove( proj )
            shutil.copy( proj+".orig", proj )
          
          shutil.copy( proj, proj+".orig" )
          self.replaceInFile( proj, replacement1 )
          self.replaceInFile( proj, replacement2 )

    except Exception as inst:
        print("Error: "+str(inst))
        exit()
  
  def configure(self):
    self.projects = ["dom\\projects\\"+self.version+"\\dom.vcproj", 
                     "dom\\projects\\"+self.version+"\\dom-static.vcproj", 
                     "dom\\projects\\"+self.version+"\\domTest.vcproj"]
    
    self.create3rdParty()
    VisualStudioBuilder.configure(self)
  
  def make(self ):
    os.chdir( self.extractedpath )
      
    if self.machine.bits == 64:
      for proj in self.projects:
        self.convertProjTo64(proj)
      self.convertSolutionTo64("dom\\projects\\"+self.version+"\dom.sln")

    os.environ['CL'] = '/DBOOST_FILESYSTEM_DEPRECATED'

    self.execute( "devenv dom\\projects\\"+self.version+"\dom.vcproj /Build \"Debug\" /useenv" )
    self.execute( "devenv dom\\projects\\"+self.version+"\dom.vcproj /Build \"Release\" /useenv" )
    self.execute( "devenv dom\\projects\\"+self.version+"\dom-static.vcproj /Build \"Debug\" /useenv" )
    self.execute( "devenv dom\\projects\\"+self.version+"\dom-static.vcproj /Build \"Release\" /useenv" )
    
  def install(self):
    os.chdir( self.extractedpath )
    includedir = self.targetpath()+"/include"
    libdir = self.targetpath()+"/lib"
    bindir = self.targetpath()+"/bin"
    if os.path.exists( includedir ):
      shutil.rmtree( includedir )
    self.copydir( "dom/include", includedir)
    for postfix in "", "-d":
      self.copypattern("dom\\build\\"+self.version+postfix, "^.*\\.lib$", libdir )
      self.copypattern("dom\\build\\"+self.version+postfix, "^.*\\.dll$", bindir )
      self.copypattern("dom\\build\\"+self.version+postfix, "^.*\\.exe$", bindir )

  
  #boost filesystem
  
  #copy the files in include and lib dirs
  #Collector([zlib_dir, jpeg_dir, png_dir, tiff_dir, gif_dir ], thirdPartyDir, removeandcreatedir = True )
   
  #OpenSceneGraph currently searches for the libungif version, so we rename the static libs
  #we could also update the search module (submission)   
  #shutil.copy( thirdPartyDir+"\\lib\\giflib.lib", thirdPartyDir+"\\lib\\libungif.lib" )
  #shutil.copy( thirdPartyDir+"\\lib\\giflibd.lib", thirdPartyDir+"\\lib\\libungifD.lib" )    
    
def decider( machine, dirs ):
  """ build collada for the machine in dirs """
  if machine.isLinux():  
    return ColladaDomCustomBuilder 
  elif machine.isWindows():
    return ColladaDomWinCustomBuilder
  else:
    raise Exception("Unknown platform")


BUILDER = decider
